<template>
	<base-page class="online-query-form base-form" :title="form.formName" @back="goBack">
		<view class="filter-box">
			<online-filter-box @refresh="onRefresh" @reset="onReset">
				<view slot="sort"
					style="display: flex;flex-direction: row;align-items: center;justify-content: space-between;">
					<view style="display: flex;flex-direction: row;align-items: center;">
						<view v-for="sortItem in sortList" :key="sortItem.id" @click="onSortChange(sortItem)"
							class="sort-item"
							style="display: flex;flex-direction: row;align-items: center;justify-content: center;">
							<text class="sort-txt"
								:class="{sortActive:sortInfoActive === sortItem.fieldName}">{{sortItem.showName}}</text>
							<view :class="['mobile-font' , sortItem.asc ? 'icon-asc' : 'icon-desc']"
								style="color:#707070;font-size:28rpx;"></view>
						</view>
					</view>
					<view class="nav-right" style="display: flex;flex-direction: row;align-items: center;">
						<view
							v-if="!showDelete && operationVisible(SysCustomWidgetOperationType.ADD) && !formReadOnly"
							:class="['mobile-font' , 'icon-add']" style="margin-left: 10px"
							@click="handlerOperation(getOperation(0))"></view>
						<view
							v-if="!showDelete && operationVisible(SysCustomWidgetOperationType.BATCH_DELETE) && !formReadOnly"
							:class="['mobile-font' , 'icon-delete']" style="margin-left: 10px"
							@click="showDelete = true"></view>
						<view v-if="showDelete" class="mobile-font" style="margin-left: 10px; font-size: 28rpx;"
							@click="showDelete = false">取消</view>
					</view>
				</view>
				<!-- 过滤字段 -->
				<online-custom-block subWidgetClass="filter-item" :widgetList="filterWidgetList" />
			</online-filter-box>
		</view>
		<view class="main-box">
			<!-- 列表 -->
			<u-form
				class="list"
				:label-width="(form.labelWidth || 100) + 'px'"
				label-position="left"
				style="height: 500px;"
			>
				<view style="height: 100%;">
					<custom-list
						ref="cardList" 
						height="100%"
						:isLoading="tableWidget.loading"
						:finished="tableWidget.finished"
						:dataList="tableWidget.dataList"
						@load="tableWidget.loadDataList"
					>
						<view class="list-item" v-for="(data ,index) in tableWidget.dataList" :key="index">
							<online-image-card :widget="cardWidget" :supportSelect="showDelete" :rowData="data"
								:masterTable="masterTable" :isSelect="itemIsSelect(data)"
								style="background: white; margin: 15px 0px;" @click.native="handlerEditOperation(data)"
								@select="onSelectChange" />
						</view>
					</custom-list>
				</view>
			</u-form>
			<!-- 删除菜单 -->
			<view class="menu-box flex-row-between" v-if="showDelete">
				<u-checkbox v-model="selectAll" name="aa" @change="changeSelectAll">全部</u-checkbox>
				<view class="flex-row-start">
					<view :class="['mobile-font', 'icon-delete']"></view>
					<text class="text" @click="onDeleteClick">
						删除{{selectItemList.length > 0 ? ('(' + selectItemList.length + ')') : ''}}
					</text>
				</view>
			</view>
			<!-- 弹出子表单 -->
			<u-popup v-model="showSubPage" mode="left" length="100%">
				<online-form v-if="showSubPage" :formId="subFormId" :rowData="editRowData" @close="onCloseSubForm" />
			</u-popup>
		</view>
		<u-modal v-model="showDeleteDlg" content="是否删除选中数据？" :show-cancel-button="true" @confirm="handlerBathDelete" />
	</base-page>
</template>

<script>
	import { DropdownWidget, TableWidget } from '@/utils/widget.js';
	import {
		OnlineFormMixins
	} from './onlineFormMixins.js';

	export default {
		name: 'onlineQueryForm',
		props: {
			formConfig: {
				type: Object
			}
		},
		data() {
			return {
				isReady: false,
				isUpdateFrom:0,
				// 是否显示删除按钮
				showDelete: false,
				showDeleteDlg: false,
				// 是否选中全部
				selectAll: false,
				// 删除选中项
				selectItemList: [],
				sortInfo: undefined,
				sortInfoActive: null,
				pageNum: 1,
				pageSize: 20,
				status: 'loadmore',
				tableWidget: new TableWidget(this.loadTableData, this.loadTableDataVerify, true),
			}
		},
		mixins: [OnlineFormMixins],
		provide() {
			return {
				form: () => {
					return {
						...this.form,
						getWidgetValue: this.getWidgetValue,
						onValueChange: this.onValueChange,
						getWidgetVisible: this.getWidgetVisible,
						onWidgetValueChange: this.onWidgetValueChange,
						getDictDataList: this.getDictDataList,
						getDropdownParams: this.getDropdownParams,
						getPrimaryData: this.getPrimaryData,
						masterTable: this.masterTable
					}
				}
			}
		},
		methods: {
			goBack() {
				uni.navigateBack();
			},
			closeSubPage() {
				this.showSubPage = false;
				this.$emit('changeSub');
			},
			handlerEditOperation(rowData) {
				if (this.showDelete) return;
				if (!this.operationVisible(this.SysCustomWidgetOperationType.EDIT) || this.formReadOnly) return;
				this.handlerOperation(this.getOperation(this.SysCustomWidgetOperationType.EDIT), rowData);
				this.$emit('changeSub');
			},
			onDeleteClick() {
				if (!Array.isArray(this.selectItemList) || this.selectItemList.length <= 0) return;
				this.showDeleteDlg = true;
			},
			handlerBathDelete() {
				if (!this.showDelete) return;
				this.handlerOperation(
					this.getOperation(this.SysCustomWidgetOperationType.BATCH_DELETE),
					this.selectItemList
				);
				this.showDeleteDlg = false;
			},
			onCloseSubForm(refresh) {
				this.showSubPage = false;
				this.$emit('changeSub');
				if (refresh) this.onRefresh();
			},
			onRefresh() {
				this.onCancelDelete();
				this.pageNum = 1;
				if (this.$refs.cardList) this.$refs.cardList.reset();
			},
			onReset() {
				if (Array.isArray(this.filterWidgetList)) {
					this.filterWidgetList.forEach(widget => {
						this.onValueChange(widget, undefined);
					});
					if (this.$refs.cardList) this.$refs.cardList.reset();
				}
			},
			onCancelDelete() {
				this.showDelete = false;
				this.selectAll = false;
				this.selectItemList = [];
			},
			changeSelectAll(detail) {
				if (detail.value) {
					if (this.$refs.cardList) {
						this.selectItemList = this.tableWidget.dataList;
						return;
					}
				}
				this.selectItemList = [];
			},
			onSelectChange(data, val) {
				if (val) {
					this.selectItemList.push(data);
				} else {
					this.selectItemList = this.selectItemList.filter(item => {
						return item !== data;
					});
				}
			},
			itemIsSelect(data) {
				let find = false;
				let primaryKey = ((this.queryTable.table || {}).primaryKeyColumn || {}).columnName;
				if (primaryKey) {
					for (let i = 0; i < this.selectItemList.length; i++) {
						if (this.selectItemList[i][primaryKey] === data[primaryKey]) {
							find = true;
							break;
						}
					}
				}
				return find;
			},
			onSortChange(sortInfo) {
				if (sortInfo.asc == null) {
					sortInfo.asc = true;
				} else if (sortInfo.asc === true) {
					sortInfo.asc = false;
				} else if (sortInfo.asc === false) {
					// sortInfo.asc = undefined;
					sortInfo.asc = true;
				}
				if (sortInfo.asc != null) {
					this.sortInfoActive = sortInfo.fieldName
					this.sortInfo = {
						fieldName: sortInfo.fieldName,
						asc: sortInfo.asc
					}
				} else {
					this.sortInfo = undefined;
				}
				this.onRefresh();
			},
			async loadTableData(params) {
				try {
					if (params == null) params = {};
					let _this = this;

					let table = _this.form.tableMap.get(_this.masterTable.tableId);
					if (table == null) {
						throw new Error('未配置关联表');
					}
					params = {
						...params,
						datasourceId: table.datasource.datasourceId,
						filterDtoList: _this.getQueryParams(_this.filterWidgetList),
						orderParam: _this.sortInfo == null ? [] : [_this.sortInfo]
					}
					if (_this.queryTable.relation != null) {
						params.relationId = table.relation.relationId;
						params.filterDtoList.push({
							tableName: _this.queryTable.table.tableName,
							columnName: _this.queryTable.relation.slaveColumn.columnName,
							filterType: _this.SysOnlineColumnFilterType.EQUAL_FILTER,
							columnValue: (_this.masterTableData || {})[_this.queryTable.relation
								.masterColumn.columnName]
						});
					}
					// 脱敏设置
					params.ignoreMaskFields = _this.getIgnoreMaskFields(_this.queryTable);
					if (_this.queryTable.eventInfo && typeof _this.queryTable.eventInfo[_this.OnlineFormEventType
							.BEFORE_LOAD_TABLE_DATA] === 'function') {
						params = await _this.queryTable.eventInfo[_this.OnlineFormEventType.BEFORE_LOAD_TABLE_DATA](
							params);
					}
					if (params == null) {
						throw new Error('未配置查询参数');
					}
					let res = null;
					if (table.relation != null) {
						res = await _this.doUrl(
							`/admin/online/onlineOperation/listByOneToManyRelationId/${table.datasource.variableName}`,
							'post', params)
					} else {
						res = await _this.doUrl(
							`/admin/online/onlineOperation/listByDatasourceId/${table.datasource.variableName}`,
							'post', params);
					}
					if (_this.queryTable.eventInfo && typeof _this.queryTable.eventInfo[_this
							.OnlineFormEventType.AFTER_LOAD_TABLE_DATA] === 'function') {
						res.dataList = await _this.queryTable.eventInfo[_this.OnlineFormEventType
							.AFTER_LOAD_TABLE_DATA](res.dataList);
					}
					return {
						dataList: res.dataList,
						totalCount: res.totalCount
					};
				} catch (e) {
					console.error(e);
					throw e;
				}
			},
			loadTableDataVerify() {
				return true
			},
			getListParent(sender) {
				return sender.$parent.$parent;
			}
		},
		computed: {
			form() {
				this.isUpdateFrom++
				return this.buildFormConfig(this.formConfig);
			},
			queryTable() {
				return this.form.tableWidget;
			},
			cardWidget() {
				return this.form.tableWidget.childWidgetList[0];
			},
			filterWidgetList() {
				return this.form.tableWidget.childWidgetList.slice(1);
			},
			sortList() {
				return this.queryTable.props.orderList.map(item => {
					let table = this.form.tableMap ? this.form.tableMap.get(item.tableId) : null;
					let column = this.form.columnMap ? this.form.columnMap.get(item.columnId) : null;
					if ((this.masterTable || {}).tableId === (table || {}).tableId) {
						// 主表字段
						return {
							...item,
							fieldName: column.columnName,
							asc: undefined
						}
					} else {
						// 从表字段
						return {
							...item,
							fieldName: table.tableName + '.' + column.columnName,
							asc: undefined
						}
					}
				});
			}
		},
		watch: {
			isUpdateFrom: {
				handler() {
					this.isReady = false;
					this.initPage();
					this.initFormWidgetList();
					if (this.form.eventInfo && typeof this.form.eventInfo["formCreated"] === 'function') {
						this.form.eventInfo["formCreated"]();
					}
					this.initWidgetLinkage(this.form.formType);
					this.isReady = true;
				},
				immediate: true
			}
		},
		mounted() {
			this.$nextTick(() => {
				this.$refs.cardList.reset();
			})
		}
	}
</script>

<style lang="less" scoped>
	.online-query-form {
		height: 100vh;
		background: #F6F7F9;
		position: relative;
		z-index: 1;
		display: flex;
		flex-direction: column;

		.filter-box {
			background: white;
			padding: 0px 36rpx;
			flex-grow: 0;
			flex-shrink: 0;
		}

		.sort-item+.sort-item {
			margin-left: 16rpx;
		}

		.sort-txt {
			font-size: 28rpx;
			color: #707070;
			margin-right: 2rpx;
		}

		.list {
			flex-grow: 1;
			flex-shrink: 1;
			padding: 4rpx 32rpx 32rpx 32rpx;
			position: relative;
		}

		.menu-box {
			flex-grow: 0;
			flex-shrink: 0;
			height: 100rpx;
			line-height: 100rpx;
			z-index: 999;
			padding: 0 32rpx;
			background-color: #ffffff;

			.mobile-font {
				font-size: 36rpx;
				color: rgb(238, 10, 36);
			}

			.text {
				font-size: 30rpx;
				color: rgb(238, 10, 36);
				margin-left: 10rpx;
			}
		}
	}

	.nav-right {
		display: flex;

		.mobile-font {
			color: #707070;
			font-size: 36rpx;

			&+.mobile-font {
				margin-left: 12rpx;
			}
		}
	}

	.main-box {
		display: flex;
		flex-direction: column;
		height: 100%;
	}

	.filter-item .u-col {
		margin-top: 20rpx;
	}
</style>